<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑权限' : '新增权限'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="权限名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入权限名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="权限码" prop="code">
        <el-input
          v-model="form.code"
          placeholder="请输入权限码，如：user:create"
          maxlength="50"
          show-word-limit
          :disabled="isEdit"
        />
        <div class="form-tip">
          权限码格式：模块:操作，如 user:create、user:update、user:delete
        </div>
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入权限描述"
          :rows="3"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createPermission, updatePermission, type Permission } from '@/api/permission'

interface Props {
  visible: boolean
  permissionData?: Permission | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 是否为编辑模式
const isEdit = computed(() => !!props.permissionData)

// 表单数据
const form = reactive({
  name: '',
  code: '',
  description: '',
  status: 1
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限码', trigger: 'blur' },
    { min: 2, max: 50, message: '权限码长度在 2 到 50 个字符', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*:[a-zA-Z][a-zA-Z0-9_]*$/, 
      message: '权限码格式不正确，应为：模块:操作', 
      trigger: 'blur' 
    }
  ],
  description: [
    { max: 200, message: '描述长度不能超过 200 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 监听权限数据变化
watch(() => props.permissionData, (permissionData) => {
  if (permissionData) {
    form.name = permissionData.name
    form.code = permissionData.code
    form.description = permissionData.description
    form.status = permissionData.status
  } else {
    resetForm()
  }
}, { immediate: true })

// 重置表单
function resetForm() {
  form.name = ''
  form.code = ''
  form.description = ''
  form.status = 1
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        if (isEdit.value) {
          await updatePermission(props.permissionData!.id, {
            name: form.name,
            code: form.code,
            description: form.description,
            status: form.status
          })
          ElMessage.success('更新权限成功')
        } else {
          await createPermission({
            name: form.name,
            code: form.code,
            description: form.description,
            status: form.status
          })
          ElMessage.success('创建权限成功')
        }
        
        emit('success')
        handleClose()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 关闭对话框
function handleClose() {
  dialogVisible.value = false
  formRef.value?.resetFields()
  resetForm()
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}
</style>
